﻿using Sunboxsoft.ASMS.Server.Domain.Calc;
using Sunboxsoft.ASMS.Server.Domain.Calculation;
using Sunboxsoft.ASMS.WebUtility;
using Sunboxsoft.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sunboxsoft.ASMS.Server.Domain.Service
{
    public class CreateService
    {
        public SingleResult<Entity.ECustomer> CreateCustomer(Entity.ECustomer customer)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                if (dbContext.Set<Entity.ECustomer>().Where(p => p.Telephone == customer.Telephone).Select(p => p.Id).Count() > 0)
                {
                    return new SingleResult<Entity.ECustomer>(1, "telephone is exist!");
                }
                customer.Id = Guid.NewGuid();
                customer.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.Code.Customer);
                customer.CreatedTime = DateTime.Now;
                customer.Status = Constant.CommonStatus.Enabled;
                customer.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();

                dbContext.Set<Entity.ECustomer>().Add(customer);
                try
                {
                    dbContext.SaveChanges();
                    return new SingleResult<Entity.ECustomer>(customer);
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("create customer error,ex:{0}", ex));
                    return new SingleResult<Entity.ECustomer>(1, ex.ToString());
                }
            }
        }

        /// <summary>
        /// 创建预约单
        /// </summary>
        /// <param name="bill"></param>
        /// <param name="services"></param>
        /// <returns></returns>
        public ServiceResult CreateBookingBill(Entity.EBookingBill bill, Entity.EBookingService[] services)
        {
            lock (Server.ServerData.BookingBillLockObject)
            {
                // 生成订单号
                using (ASMSDbContext dbContext = new ASMSDbContext())
                {
                    bill.Id = Guid.NewGuid();
                    bill.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.BookingBill);
                    bill.Status = Constant.BookingBillStatus.Normal;
                    bill.CreatedTime = DateTime.Now;
                    bill.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();

                    dbContext.Set<Entity.EBookingBill>().Add(bill);
                    for (int index = 0; index < services.Length; index++)
                    {
                        services[index].Id = Guid.NewGuid();
                        services[index].BillId = bill.Id;
                        dbContext.Set<Entity.EBookingService>().Add(services[index]);
                    }

                    PrivateCreateSerivce.CreateBillHeader(dbContext, bill.Id, bill.Number, Constant.BillTypes.BookingBill, bill.CreatedTime, bill.Creator);

                    try
                    {
                        dbContext.SaveChanges();
                        return new ServiceResult();
                    }
                    catch (Exception ex)
                    {
                        Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.BookingBill);
                        Logger.ErrorToTag(Library.LogTag, string.Format("CreateBookingBill error:{0}", ex.ToString()));
                        return new ServiceResult(1, ex.ToString());
                    }
                }
            }
        }

        /// <summary>
        /// 创建服务商
        /// </summary>
        /// <param name="business"></param>
        /// <returns></returns>
        public ServiceResult CreateBusiness(Entity.EBusiness business)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                if (dbContext.Set<Entity.EBusiness>().Where(p => p.Number == business.Number).Select(p => p.Id).Count() > 0)
                {
                    return new ServiceResult(1, "number is exist");
                }
                DateTime now = DateTime.Now;
                business.Id = Guid.NewGuid();
                business.CreatedTime = now;
                business.Creator = CookieUtility.GetUserIdString();
                business.Status = Constant.CommonStatus.Enabled;
                dbContext.Set<Entity.EBusiness>().Add(business);
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateBusiness error,ex:{0}", ex));
                    return new ServiceResult(1, ex.ToString());
                }
            }
        }

        public ServiceResult CreateAutomobile(Entity.EAutomobile automobile)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                if (dbContext.Set<Entity.EAutomobile>().Where(p => p.CustomerId == automobile.CustomerId).Select(p => p.Id).Count() >= 2)
                {
                    return new ServiceResult(1, "超过最大汽车数量!");
                }
                if (dbContext.Set<Entity.EAutomobile>().Where(p => p.LPN == automobile.LPN).Select(p => p.Id).Count() > 0)
                {
                    return new ServiceResult(1, "车牌号已存在,无法创建!");
                }
                automobile.Id = Guid.NewGuid();
                automobile.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.Code.Automobile);
                automobile.CreatedTime = DateTime.Now;
                automobile.Status = Constant.CommonStatus.Enabled;
                automobile.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();

                dbContext.Set<Entity.EAutomobile>().Add(automobile);
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateAutomobile error,ex:{0}", ex));
                    return new ServiceResult(1, ex.ToString());
                }
            }
        }

        public ServiceResult CreateServiceCategory(Entity.EServiceCategory category)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                category.Id = Guid.NewGuid();
                category.Status = Constant.CommonStatus.Enabled;
                category.SortIndex = 1;
                category.CreatedTime = DateTime.Now;
                category.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();

                dbContext.Set<Entity.EServiceCategory>().Add(category);
                // 创建一个主数据项目
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateServiceCategory error,ex:{0}", ex));
                    return new ServiceResult(1, ex.ToString());
                }
            }
        }

        /// <summary>
        /// 创建服务项目
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public ServiceResult CreateServiceItem(Entity.EServiceItem item)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                item.Id = Guid.NewGuid();
                item.Code = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.Code.ServiceItem);
                item.Status = Constant.CommonStatus.WaitAuditing;
                item.SortIndex = 1;
                item.CreatedTime = DateTime.Now;
                item.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();

                dbContext.Set<Entity.EServiceItem>().Add(item);
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.Code.ServiceItem);
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateServiceItem error,ex:{0}", ex));
                    return new ServiceResult(1, ex.ToString());
                }
            }
        }

        public ServiceResult CreateServiceItemRetain(Entity.EServiceItemRetain retain, Guid businessId, Guid[] stationIdArray)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                DateTime now = DateTime.Now;
                if (stationIdArray == null || stationIdArray.Length == 0)
                {
                    Entity.EServiceItemRetain item = dbContext.Set<Entity.EServiceItemRetain>().SingleOrDefault(p => p.ServiceItemId == retain.ServiceItemId
                        && p.BusinessId == businessId && p.StationId == null);
                    if (item == null)
                    {
                        item = new Entity.EServiceItemRetain();
                        item.Id = Guid.NewGuid();
                        item.BusinessId = businessId;
                        item.StationId = null;
                        item.ServiceItemId = retain.ServiceItemId;
                        item.Status = Constant.CommonStatus.Enabled;
                        item.CreatedTime = now;
                        item.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                        item.Price = retain.Price;
                        item.Discount = retain.Discount;
                        item.SalesCommission = retain.SalesCommission;
                        item.SalesCommissionType = retain.SalesCommissionType;
                        item.TechnicianCommission = retain.TechnicianCommission;
                        item.TechnicianCommissionType = retain.TechnicianCommissionType;
                        item.TaxRate = retain.TaxRate;
                        dbContext.Set<Entity.EServiceItemRetain>().Add(item);
                    }
                    else
                    {
                        item.Price = retain.Price;
                        item.Discount = retain.Discount;
                        item.SalesCommission = retain.SalesCommission;
                        item.SalesCommissionType = retain.SalesCommissionType;
                        item.TechnicianCommission = retain.TechnicianCommission;
                        item.TechnicianCommissionType = retain.TechnicianCommissionType;
                        item.TaxRate = retain.TaxRate;

                        dbContext.Entry<Entity.EServiceItemRetain>(item).State = System.Data.Entity.EntityState.Modified;
                    }
                }
                else
                {
                    for (int index = 0; index < stationIdArray.Length; index++)
                    {
                        Guid stationId = stationIdArray[index];
                        Entity.EServiceItemRetain item = dbContext.Set<Entity.EServiceItemRetain>().SingleOrDefault(p => p.ServiceItemId == retain.ServiceItemId
                            && p.BusinessId == businessId && p.StationId == stationId);
                        if (item == null)
                        {
                            item = new Entity.EServiceItemRetain();
                            item.Id = Guid.NewGuid();
                            item.BusinessId = businessId;
                            item.StationId = stationIdArray[index];
                            item.ServiceItemId = retain.ServiceItemId;
                            item.Status = Constant.CommonStatus.Enabled;
                            item.CreatedTime = now;
                            item.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                            item.Price = retain.Price;
                            item.Discount = retain.Discount;
                            item.SalesCommission = retain.SalesCommission;
                            item.SalesCommissionType = retain.SalesCommissionType;
                            item.TechnicianCommission = retain.TechnicianCommission;
                            item.TechnicianCommissionType = retain.TechnicianCommissionType;
                            item.TaxRate = retain.TaxRate;
                            dbContext.Set<Entity.EServiceItemRetain>().Add(item);
                        }
                        else
                        {
                            item.Price = retain.Price;
                            item.Discount = retain.Discount;
                            item.SalesCommission = retain.SalesCommission;
                            item.SalesCommissionType = retain.SalesCommissionType;
                            item.TechnicianCommission = retain.TechnicianCommission;
                            item.TechnicianCommissionType = retain.TechnicianCommissionType;
                            item.TaxRate = retain.TaxRate;

                            dbContext.Entry<Entity.EServiceItemRetain>(item).State = System.Data.Entity.EntityState.Modified;
                        }
                    }
                }
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateServiceItemRetain error,ex:{0}", ex));
                    return new ServiceResult(1, ex.ToString());
                }
            }
        }

        public ServiceResult CreateMaterialRetain(Entity.EMaterialRetain retain, Guid businessId, Guid[] stationIdArray)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                DateTime now = DateTime.Now;
                if (stationIdArray == null || stationIdArray.Length == 0)
                {
                    Entity.EMaterialRetain item = dbContext.Set<Entity.EMaterialRetain>().SingleOrDefault(p => p.MaterialId == retain.MaterialId
                        && p.BusinessId == businessId && p.StationId == null);
                    if (item == null)
                    {
                        item = new Entity.EMaterialRetain();
                        item.Id = Guid.NewGuid();
                        item.BusinessId = businessId;
                        item.StationId = null;
                        item.MaterialId = retain.MaterialId;
                        item.Status = Constant.CommonStatus.Enabled;
                        item.CreatedTime = now;
                        item.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                        item.Price = retain.Price;
                        item.Cost = retain.Cost;
                        item.SalesCommission = retain.SalesCommission;
                        item.SalesCommissionType = retain.SalesCommissionType;
                        item.TaxRate = retain.TaxRate;
                        dbContext.Set<Entity.EMaterialRetain>().Add(item);
                    }
                    else
                    {
                        item.Price = retain.Price;
                        item.Cost = retain.Cost;
                        item.SalesCommission = retain.SalesCommission;
                        item.SalesCommissionType = retain.SalesCommissionType;
                        item.TaxRate = retain.TaxRate;
                        dbContext.Entry<Entity.EMaterialRetain>(item).State = System.Data.Entity.EntityState.Modified;
                    }
                }
                else
                {
                    for (int index = 0; index < stationIdArray.Length; index++)
                    {
                        Guid stationId = stationIdArray[index];
                        Entity.EMaterialRetain item = dbContext.Set<Entity.EMaterialRetain>().SingleOrDefault(p => p.MaterialId == retain.MaterialId
                            && p.BusinessId == businessId && p.StationId == stationId);
                        if (item == null)
                        {
                            item = new Entity.EMaterialRetain();
                            item.Id = Guid.NewGuid();
                            item.BusinessId = businessId;
                            item.StationId = stationIdArray[index];
                            item.MaterialId = retain.MaterialId;
                            item.Status = Constant.CommonStatus.Enabled;
                            item.CreatedTime = now;
                            item.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                            item.Price = retain.Price;
                            item.Cost = retain.Cost;
                            item.SalesCommission = retain.SalesCommission;
                            item.SalesCommissionType = retain.SalesCommissionType;
                            item.TaxRate = retain.TaxRate;
                            dbContext.Set<Entity.EMaterialRetain>().Add(item);
                        }
                        else
                        {
                            item.Price = retain.Price;
                            item.Cost = retain.Cost;
                            item.SalesCommission = retain.SalesCommission;
                            item.SalesCommissionType = retain.SalesCommissionType;
                            item.TaxRate = retain.TaxRate;

                            dbContext.Entry<Entity.EMaterialRetain>(item).State = System.Data.Entity.EntityState.Modified;
                        }
                    }
                }
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateMaterialRetain error,ex:{0}", ex));
                    return new ServiceResult(1, ex.ToString());
                }
            }
        }

        public SingleResult<Entity.EMaintenanceBill> CreateMaintenanceBill(Entity.EMaintenanceBill bill, Entity.EMaintenanceBillServiceItem[] serviceItemArray,
            Entity.EMaintenanceBillMaterial[] materialArray,
            Entity.EMaintenanceBillPayItem[] payItemArray)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                if (bill.BookingBillId != null)
                {
                    Entity.EBookingBill bookingBill = dbContext.Set<Entity.EBookingBill>().SingleOrDefault(p => p.Id == bill.BookingBillId.Value);
                    if (bookingBill == null)
                    {
                        return new SingleResult<Entity.EMaintenanceBill>(1, "预约单不存在");
                    }
                    bookingBill.Status = Constant.BookingBillStatus.Working;
                    dbContext.Entry<Entity.EBookingBill>(bookingBill).State = System.Data.Entity.EntityState.Modified;
                }

                bill.Id = Guid.NewGuid();
                bill.Status = Constant.MaintenanceBillStatus.WaitDispatching;
                bill.CreatedTime = DateTime.Now;
                bill.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.MaintenaceBill);
                bill.Amount = MaintanceBillCalculation.Calc(serviceItemArray, materialArray, payItemArray);
                bill.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();

                if (serviceItemArray != null)
                {
                    for (int index = 0; index < serviceItemArray.Length; index++)
                    {
                        serviceItemArray[index].Id = Guid.NewGuid();
                        serviceItemArray[index].MaintenanceBillId = bill.Id;
                        serviceItemArray[index].Status = Constant.CommonStatus.Enabled;
                        serviceItemArray[index].Amount = serviceItemArray[index].Price *  serviceItemArray[index].Hour * serviceItemArray[index].Discount;
                        serviceItemArray[index].SalesCommissionAmount = Calc.CalcUtil.CalcCommissionAmount(serviceItemArray[index].Amount,
                            serviceItemArray[index].SalesCommissionType,
                            serviceItemArray[index].SalesCommission);
                        serviceItemArray[index].TechnicianCommissionAmount = Calc.CalcUtil.CalcCommissionAmount(serviceItemArray[index].Amount,
                            serviceItemArray[index].TechnicianCommissionType,
                            serviceItemArray[index].TechnicianCommission);
                        dbContext.Set<Entity.EMaintenanceBillServiceItem>().Add(serviceItemArray[index]);
                    }
                    bill.ServiceItemCount = serviceItemArray.Length;
                }

                if (materialArray != null)
                {
                    for (int index = 0; index < materialArray.Length; index++)
                    {
                        materialArray[index].Id = Guid.NewGuid();
                        materialArray[index].MaintenanceBillId = bill.Id;
                        materialArray[index].Status = Constant.CommonStatus.Enabled;
                        materialArray[index].Amount = materialArray[index].Price * materialArray[index].Count * materialArray[index].Discount;
                        materialArray[index].SalesCommissionAmount = Calc.CalcUtil.CalcCommissionAmount(materialArray[index].Amount,
                            materialArray[index].SalesCommissionType,
                            materialArray[index].SalesCommission);
                        dbContext.Set<Entity.EMaintenanceBillMaterial>().Add(materialArray[index]);
                    }
                    bill.MaterialCount = materialArray.Length;
                }
                if (bill.ServiceItemCount == 0)
                {
                    bill.ServiceItemStatus = Constant.MaintenanceBillStatus.ServiceItemStatus.Finished;
                }
                else
                {
                    bill.ServiceItemStatus = Constant.MaintenanceBillStatus.ServiceItemStatus.Wait;
                }

                if (bill.MaterialCount == 0)
                {
                    bill.MaterialStatus = Constant.MaintenanceBillStatus.MaterialStatus.Finished;
                }
                else
                {
                    bill.MaterialStatus = Constant.MaintenanceBillStatus.MaterialStatus.Wait;
                }

                if (payItemArray != null)
                {
                    for (int index = 0; index < payItemArray.Length; index++)
                    {
                        payItemArray[index].Id = Guid.NewGuid();
                        payItemArray[index].MaintenanceBillId = bill.Id;
                        payItemArray[index].Status = Constant.CommonStatus.Enabled;
                        dbContext.Set<Entity.EMaintenanceBillPayItem>().Add(payItemArray[index]);
                    }
                    bill.PayItemCount = payItemArray.Length;
                }


                dbContext.Set<Entity.EMaintenanceBill>().Add(bill);

                PrivateCreateSerivce.CreateBillHeader(dbContext, bill.Id, bill.Number, Constant.BillTypes.MaintenanceBill, bill.CreatedTime, bill.Creator);

                try
                {
                    dbContext.SaveChanges();
                    return new SingleResult<Entity.EMaintenanceBill>(bill);
                }
                catch (Exception ex)
                {
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.MaintenaceBill);
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateMaintenanceBill error:{0}", ex.ToString()));
                    return new SingleResult<Entity.EMaintenanceBill>(1, ex.Message);
                }
            }
        }

        public ServiceResult CreatePayItem(Entity.EPayItem payItem)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                if (string.IsNullOrEmpty(payItem.Code))
                {
                    return new ServiceResult(1, "code can't be null");
                }
                if (dbContext.Set<Entity.EPayItem>().Where(p => p.Code == payItem.Code).Select(p => p.Id).Count() > 0)
                {
                    return new ServiceResult(1, "code exist");
                }
                payItem.Id = Guid.NewGuid();
                payItem.Status = Constant.CommonStatus.Enabled;
                payItem.CreatedTime = DateTime.Now;
                payItem.BusinessId = WebUtility.CookieUtility.GetBusinessId();
                payItem.StationId = WebUtility.CookieUtility.GetStationId();
                payItem.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();

                dbContext.Set<Entity.EPayItem>().Add(payItem);
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreatePayItem error,ex:{0}", ex));
                    return new ServiceResult(1, ex.ToString());
                }
            }
        }

        public SingleResult<Entity.EMaterial> CreateMaterial(Entity.EMaterial material)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                material.Id = Guid.NewGuid();
                material.Code = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.Code.Material);
                material.Status = Constant.CommonStatus.WaitAuditing;
                material.CreatedTime = DateTime.Now;
                material.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();

                dbContext.Set<Entity.EMaterial>().Add(material);
                try
                {
                    dbContext.SaveChanges();
                    return new SingleResult<Entity.EMaterial>(material);
                }
                catch (Exception ex)
                {
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.Code.Material);
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateMaterial error,ex:{0}", ex));
                    return new SingleResult<Entity.EMaterial>(1, ex.ToString());
                }
            }
        }

        public ServiceResult CreateWarehouse(Entity.EWarehouse warehouse)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                warehouse.Id = Guid.NewGuid();
                warehouse.Status = Constant.CommonStatus.Enabled;
                warehouse.CreatedTime = DateTime.Now;
                warehouse.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();

                dbContext.Set<Entity.EWarehouse>().Add(warehouse);
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateWarehouse error,ex:{0}", ex));
                    return new ServiceResult(1, ex.ToString());
                }
            }
        }

        /// <summary>
        /// 创建门店
        /// </summary>
        /// <param name="station"></param>
        /// <returns></returns>
        public ServiceResult CreateStation(Entity.EStation station)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                if (dbContext.Set<Entity.EStation>().Where(p => p.Number == station.Number && p.BusinessId == station.BusinessId).Select(p => p.Id).Count() > 0)
                {
                    return new ServiceResult(1, "number is exist");
                }
                DateTime now = DateTime.Now;
                station.Id = Guid.NewGuid();
                station.CreatedTime = now;
                station.Creator = CookieUtility.GetUserIdString();
                station.Status = Constant.CommonStatus.WaitAuditing;
                dbContext.Set<Entity.EStation>().Add(station);
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateStation error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        public ServiceResult CreateStaff(Entity.EStaff staff, Entity.EStaffPosition[] staffPositionArray)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                if (dbContext.Set<Entity.EStaff>().Where(p => p.Account == staff.Account).Select(p => p.Id).Count() > 0)
                {
                    return new ServiceResult(1, "account is exist");
                }

                if (!string.IsNullOrEmpty(staff.IdNumber))
                {
                    if (dbContext.Set<Entity.EStaff>().Where(p => p.IdNumber == staff.IdNumber).Select(p => p.Id).Count() > 0)
                    {
                        return new ServiceResult(1, "IdNumber is exist");
                    }
                }
                DateTime now = DateTime.Now;
                staff.Id = Guid.NewGuid();
                staff.CreatedTime = now;
                staff.Password = Common.Utility.MD5Utility.GetStringX(staff.Password);
                staff.Creator = CookieUtility.GetUserIdString();
                staff.Status = Constant.CommonStatus.Enabled;
                dbContext.Set<Entity.EStaff>().Add(staff);

                if (staffPositionArray != null && staffPositionArray.Length > 0)
                {
                    List<string> uniqueKeyList = new List<string>();
                    for (int index = 0; index < staffPositionArray.Length; index++)
                    {
                        string uniqueKey = string.Format("{0}{1}", staffPositionArray[index].StationId, staffPositionArray[index].Post);
                        if(uniqueKeyList.Contains(uniqueKey))
                        {
                            continue;
                        }
                        staffPositionArray[index].StaffId = staff.Id;
                        staffPositionArray[index].Status = Constant.CommonStatus.Enabled;
                        staffPositionArray[index].CreatedTime = now;
                        staffPositionArray[index].Creator = CookieUtility.GetUserIdString();
                        staffPositionArray[index].Status = Constant.CommonStatus.Enabled;
                        dbContext.Set<Entity.EStaffPosition>().Add(staffPositionArray[index]);
                        uniqueKeyList.Add(uniqueKey);
                    }
                }

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateStaff error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        #region stock
        public ServiceResult CreateStockIncreaseBill(Entity.EStockIncreaseBill bill, Entity.EStockIncreaseBillItem[] itemArray)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                DateTime now = DateTime.Now;

                bill.Id = Guid.NewGuid();
                bill.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.StockIncreaseBill);
                bill.Status = Constant.CommonStatus.Enabled;
                bill.CreatedTime = now;
                bill.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                dbContext.Set<Entity.EStockIncreaseBill>().Add(bill);

                for(int index = 0; index < itemArray.Length; index++)
                {
                    Entity.EStockIncreaseBillItem item = itemArray[index];
                    item.StockIncreaseBillId = bill.Id;
                    item.WarehouseId = bill.WarehouseId;
                    item.Id = Guid.NewGuid();
                    dbContext.Set<Entity.EStockIncreaseBillItem>().Add(item);

                    Entity.EStock stock = dbContext.Set<Entity.EStock>().Where(p => p.WarehouseId == bill.WarehouseId && p.MaterialId == item.MaterialId).SingleOrDefault();

                    if (stock == null)
                    {
                        // 创建库存信息
                        stock = new Entity.EStock();
                        stock.Id = Guid.NewGuid();
                        stock.WarehouseId = bill.WarehouseId;
                        stock.MaterialId = item.MaterialId;
                        stock.Cost = item.Cost;
                        stock.Count = item.Count;
                        if (stock.Count == 0)
                        {
                            stock.AverageCost = stock.Cost;
                        }
                        else
                        {
                            stock.AverageCost = stock.Cost / stock.Count;
                        }
                        stock.UpdatedTime = now;
                        stock.Updator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                        dbContext.Set<Entity.EStock>().Add(stock);
                    }
                    else
                    {
                        stock.Cost += item.Cost * item.Count;
                        stock.Count += item.Count;
                        if (stock.Count == 0)
                        {
                            stock.AverageCost = stock.Cost;
                        }
                        else
                        {
                            stock.AverageCost = stock.Cost / stock.Count;
                        }
                        stock.UpdatedTime = now;
                        stock.Updator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                        dbContext.Entry<Entity.EStock>(stock).State = System.Data.Entity.EntityState.Modified;
                    }
                    // 生成库存变更记录
                    Entity.EStockChangedRecord changeRecord = new Entity.EStockChangedRecord();
                    changeRecord.Id = Guid.NewGuid();
                    changeRecord.Type = bill.Type;
                    changeRecord.WarehouseId = bill.WarehouseId;
                    changeRecord.MaterialId = item.MaterialId;
                    changeRecord.BillId = bill.Id;
                    changeRecord.BillNumber = bill.Number;
                    changeRecord.BillType = Constant.BillTypes.StockIncreaseBill;
                    changeRecord.StockId = stock.Id;
                    changeRecord.Cost = item.Cost * item.Count;
                    changeRecord.Count = item.Count;
                    changeRecord.RemainingCost = stock.Cost;
                    changeRecord.RemainingCount = stock.Count;
                    changeRecord.CreatedTime = now;
                    changeRecord.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                    dbContext.Set<Entity.EStockChangedRecord>().Add(changeRecord);
                }

                PrivateCreateSerivce.CreateBillHeader(dbContext, bill.Id, bill.Number, Constant.BillTypes.StockIncreaseBill, bill.CreatedTime, bill.Creator);

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateStockIncreaseBill error,ex:{0}", ex));
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.StockIncreaseBill);
                    return new ServiceResult(1, ex.ToString());
                }
            }
        }

        public ServiceResult CreateStockDecreaseBill(Entity.EStockDecreaseBill bill, Entity.EStockDecreaseBillItem[] itemArray)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                DateTime now = DateTime.Now;

                bill.Id = Guid.NewGuid();
                bill.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.StockDecreaseBill);
                bill.Status = Constant.CommonStatus.Enabled;
                bill.CreatedTime = now;
                bill.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                dbContext.Set<Entity.EStockDecreaseBill>().Add(bill);

                for (int index = 0; index < itemArray.Length; index++)
                {
                    Entity.EStockDecreaseBillItem item = itemArray[index];
                    item.StockDecreaseBillId = bill.Id;
                    item.Id = Guid.NewGuid();
                    dbContext.Set<Entity.EStockDecreaseBillItem>().Add(item);

                    Entity.EStock stock = dbContext.Set<Entity.EStock>().Where(p => p.WarehouseId == item.WarehouseId && p.MaterialId == item.MaterialId).SingleOrDefault();

                    if (stock == null)
                    {
                        return new ServiceResult(1, "not enough stock");
                    }
                    else
                    {
                        stock.Cost -= item.Price * item.Count;
                        stock.Count -= item.Count;
                        if (stock.Count == 0)
                        {
                            stock.AverageCost = stock.Cost;
                        }
                        else
                        {
                            stock.AverageCost = stock.Cost / stock.Count;
                        }
                        stock.UpdatedTime = now;
                        stock.Updator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                        dbContext.Entry<Entity.EStock>(stock).State = System.Data.Entity.EntityState.Modified;
                    }
                    // 生成库存变更记录
                    Entity.EStockChangedRecord changeRecord = new Entity.EStockChangedRecord();
                    changeRecord.Id = Guid.NewGuid();
                    changeRecord.Type = bill.Type;
                    changeRecord.WarehouseId = item.WarehouseId;
                    changeRecord.MaterialId = item.MaterialId;
                    changeRecord.BillId = bill.Id;
                    changeRecord.BillNumber = bill.Number;
                    changeRecord.BillType = Constant.BillTypes.StockDecreaseBill;
                    changeRecord.StockId = stock.Id;
                    changeRecord.Cost = item.Price * item.Count;
                    changeRecord.Count = item.Count;
                    changeRecord.RemainingCost = stock.Cost;
                    changeRecord.RemainingCount = stock.Count;
                    changeRecord.CreatedTime = now;
                    changeRecord.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                    dbContext.Set<Entity.EStockChangedRecord>().Add(changeRecord);
                }

                PrivateCreateSerivce.CreateBillHeader(dbContext, bill.Id, bill.Number, Constant.BillTypes.StockDecreaseBill, bill.CreatedTime, bill.Creator);
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateStockDecreaseBill error,ex:{0}", ex));
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.StockDecreaseBill);
                    return new ServiceResult(1, ex.ToString());
                }
            }
        }

        public ServiceResult CreateStockThresholdValue(Entity.EStockThresholdValue thresholdValue)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                DateTime now = DateTime.Now;
                Entity.EStockThresholdValue existThresholdValue = dbContext.Set<Entity.EStockThresholdValue>().SingleOrDefault(p => p.WarehouseId == thresholdValue.WarehouseId && p.MaterialId == thresholdValue.MaterialId);
                if (existThresholdValue != null)
                {
                    existThresholdValue.Value = thresholdValue.Value;
                    existThresholdValue.CreatedTime = now;
                    existThresholdValue.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                    existThresholdValue.Status = Constant.CommonStatus.Enabled;
                    dbContext.Entry<Entity.EStockThresholdValue>(existThresholdValue).State = System.Data.Entity.EntityState.Modified;
                }
                else
                {
                    thresholdValue.Id = Guid.NewGuid();
                    thresholdValue.CreatedTime = now;
                    thresholdValue.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                    thresholdValue.Status = Constant.CommonStatus.Enabled;
                    dbContext.Set<Entity.EStockThresholdValue>().Add(thresholdValue);
                }

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateStockWarning error,ex:{0}", ex));
                    return new ServiceResult(1, ex.ToString());
                }
            }

        }

        #endregion

        /// <summary>
        /// 创建供应商，供应商的状态为等待审核
        /// </summary>
        /// <param name="supplier"></param>
        /// <returns></returns>
        public ServiceResult CreateSupplier(Entity.ESupplier supplier)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                DateTime now = DateTime.Now;
                supplier.Id = Guid.NewGuid();
                supplier.Code = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.Code.Supplier);
                supplier.CreatedTime = now;
                supplier.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                supplier.Status = Constant.CommonStatus.WaitAuditing;
                dbContext.Set<Entity.ESupplier>().Add(supplier);
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.Code.Supplier);
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateSupplier error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }


        /// <summary>
        /// create working bill
        /// </summary>
        /// <param name="workingBill"></param>
        /// <returns></returns>
        public ServiceResult CreateWorkingBill(Entity.EWorkingBill workingBill)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                Entity.EMaintenanceBill maintenanceBill = dbContext.Set<Entity.EMaintenanceBill>().SingleOrDefault(p => p.Id == workingBill.MaintenanceBillId);
                if (maintenanceBill == null)
                {
                    return new ServiceResult(1, "maintenanceBill not exist! ");
                }

                Entity.EMaintenanceBillServiceItem maintenanceBillServiceItem = dbContext.Set<Entity.EMaintenanceBillServiceItem>().SingleOrDefault(p => p.MaintenanceBillId == workingBill.MaintenanceBillId && p.Id == workingBill.MaintenanceBillServiceItemId);
                if (maintenanceBillServiceItem == null)
                {
                    return new ServiceResult(1, "maintenanceBillServiceItem not exist! ");
                }

                if (dbContext.Set<Entity.EWorkingBill>().Where(p => p.MaintenanceBillId == workingBill.MaintenanceBillId
                    && p.MaintenanceBillServiceItemId == workingBill.MaintenanceBillServiceItemId 
                    && p.Status != Constant.WorkingBillStatus.Deleted).Select(p => p.Id).Count() > 0)
                {
                    return new ServiceResult(1, "can not create working bill! ");
                }

                DateTime now  = DateTime.Now;
                workingBill.Id = Guid.NewGuid();
                workingBill.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.WorkingBill);
                workingBill.Status = Constant.WorkingBillStatus.Enabled;
                workingBill.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                workingBill.CreatedTime = now;
                dbContext.Set<Entity.EWorkingBill>().Add(workingBill);

                // 修改维修单状态为施工
                if (maintenanceBill.ServiceItemCount > 1 && dbContext.Set<View.VMaintenanceBillServiceItem>().Where(p => p.MaintenanceBillId == workingBill.MaintenanceBillId && p.WorkingBillId == null).Select(p => p.Id).Count() > 1)
                {
                    // 还有多项工作项目未派工
                    maintenanceBill.ServiceItemStatus = Constant.MaintenanceBillStatus.ServiceItemStatus.PartialWait;
                }
                else
                {
                    maintenanceBill.ServiceItemStatus = Constant.MaintenanceBillStatus.ServiceItemStatus.Working;
                }
                maintenanceBill.Status = Constant.MaintenanceBillStatus.Working;
                dbContext.Entry<Entity.EMaintenanceBill>(maintenanceBill).State = System.Data.Entity.EntityState.Modified;
                
                // 修改维修单项目的状态
                maintenanceBillServiceItem.Status = Constant.MaintenanceBillServiceItemStatus.Working;
                dbContext.Entry<Entity.EMaintenanceBillServiceItem>(maintenanceBillServiceItem).State = System.Data.Entity.EntityState.Modified;

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateWorkingBill error,ex:{0}", ex));
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.WorkingBill);
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        /// <summary>
        /// 创建领料单
        /// </summary>
        /// <param name="materialRequisitonBill"></param>
        /// <returns></returns>
        public ServiceResult CreateMaterialRequisitionBill(Entity.EMaterialRequisitionBill materialRequisitonBill)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                if (dbContext.Set<Entity.EMaterialRequisitionBill>().Where(p => p.MaintenanceBillId == materialRequisitonBill.MaintenanceBillId
                    && p.MaintenanceBillMaterialId == materialRequisitonBill.MaintenanceBillMaterialId
                    && p.Status == Constant.MaterialRequisitionStatus.Finished).Select(p => p.Id).Count() > 0)
                {
                    return new ServiceResult(1, "can not create MaterialRequisitionBill! ");
                }

                Entity.EMaintenanceBill maintenanceBill = dbContext.Set<Entity.EMaintenanceBill>().Single(p => p.Id == materialRequisitonBill.MaintenanceBillId);
                if (maintenanceBill == null)
                {
                    return new ServiceResult(1, "maintenanceBill not exist! ");
                }

                Entity.EMaintenanceBillMaterial maintenanceBillMaterial = dbContext.Set<Entity.EMaintenanceBillMaterial>().SingleOrDefault(p => p.MaintenanceBillId == materialRequisitonBill.MaintenanceBillId && p.Id == materialRequisitonBill.MaintenanceBillMaterialId);
                if (maintenanceBillMaterial == null)
                {
                    return new ServiceResult(1, "maintenanceBillMaterial not exist! ");
                }

                DateTime now = DateTime.Now;
                materialRequisitonBill.Id = Guid.NewGuid();
                materialRequisitonBill.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.MaterialRequisitionBill);
                materialRequisitonBill.Status = Constant.MaterialRequisitionStatus.Finished;
                materialRequisitonBill.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                materialRequisitonBill.CreatedTime = now;
                materialRequisitonBill.HandledTime = now;
                dbContext.Set<Entity.EMaterialRequisitionBill>().Add(materialRequisitonBill);

                if (dbContext.Set<View.VMaintenanceBillMaterial>().Where(p => p.MaintenanceBillId == materialRequisitonBill.MaintenanceBillId
                    && p.ActualFinishedTime == null).Select(p => p.Id).Count() == 1)
                {
                    // 就差一个物料为领取，将维修单设置为物料领取完毕
                    maintenanceBill.MaterialStatus = Constant.MaintenanceBillStatus.MaterialStatus.Finished;
                }
                else
                {
                    // 还有别的料未领，设置为领料中
                    maintenanceBill.MaterialStatus = Constant.MaintenanceBillStatus.MaterialStatus.Requesting;
                }

                if (maintenanceBill.MaterialStatus == Constant.MaintenanceBillStatus.MaterialStatus.Finished
                    && maintenanceBill.ServiceItemStatus == Constant.MaintenanceBillStatus.ServiceItemStatus.Finished)
                {
                    // 领料已全部完成,服务项目也全部竣工 ，更新为带结算状态
                    maintenanceBill.Status = Constant.MaintenanceBillStatus.WaitSettling;
                }
                else
                {
                    maintenanceBill.Status = Constant.MaintenanceBillStatus.Working;
                }
                dbContext.Entry<Entity.EMaintenanceBill>(maintenanceBill).State = System.Data.Entity.EntityState.Modified;

                // 更新维修单的物料为已领料
                maintenanceBillMaterial.Status = Constant.MaintenanceBillMaterialStatus.Finished;
                dbContext.Entry<Entity.EMaintenanceBillMaterial>(maintenanceBillMaterial).State = System.Data.Entity.EntityState.Modified;

                #region 创建出库记录
                ServiceResult serviceResult = InlineCreateService.CreateStockDecreaseRecord(dbContext, now,
                    maintenanceBillMaterial.Price, 
                    materialRequisitonBill.Count, 
                    Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString(),
                    Constant.BillTypes.MaterialRequisitionBill,
                    materialRequisitonBill.WarehouseId, 
                    materialRequisitonBill.MaterialId, 
                    materialRequisitonBill.Id, 
                    materialRequisitonBill.Number);
                if (!serviceResult.IsSuccess)
                {
                    return serviceResult;
                }
                #endregion

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateMaterialRequisitionBill error,ex:{0}", ex));
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.MaterialRequisitionBill);
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        /// <summary>
        /// 创建退料单
        /// </summary>
        /// <param name="materialRequisitonBill"></param>
        /// <returns></returns>
        public ServiceResult CreateMaterialReturnedBill(Entity.EMaterialReturnedBill materialReturnedBill)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                Entity.EMaterialRequisitionBill materialRequisitionBill = dbContext.Set<Entity.EMaterialRequisitionBill>().SingleOrDefault(p => p.Id == materialReturnedBill.MaterialRequisitionBillId && p.Status == Constant.MaterialRequisitionStatus.Finished);
                if (materialRequisitionBill == null)
                {
                    return new ServiceResult(1, "materialRequisitionBill not exist");
                }

                Entity.EMaintenanceBill maintenanceBill = dbContext.Set<Entity.EMaintenanceBill>().Single(p => p.Id == materialReturnedBill.MaintenanceBillId);
                if (maintenanceBill == null)
                {
                    return new ServiceResult(1, "maintenanceBill not exist!");
                }

                Entity.EMaintenanceBillMaterial maintenanceBillMaterial = dbContext.Set<Entity.EMaintenanceBillMaterial>().SingleOrDefault(p => p.MaintenanceBillId == materialReturnedBill.MaintenanceBillId && p.Id == materialReturnedBill.MaintenanceBillMaterialId);
                if (maintenanceBillMaterial == null)
                {
                    return new ServiceResult(1, "maintenanceBillMaterial not exist!");
                }

                materialRequisitionBill.Status = Constant.MaterialRequisitionStatus.Returned;
                dbContext.Entry<Entity.EMaterialRequisitionBill>(materialRequisitionBill).State = System.Data.Entity.EntityState.Modified;


                DateTime now = DateTime.Now;
                materialReturnedBill.Id = Guid.NewGuid();
                materialReturnedBill.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.MaterialReturnedBill);
                materialReturnedBill.Status = Constant.CommonBillStatus.Enabled;
                materialReturnedBill.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                materialReturnedBill.CreatedTime = now;
                materialReturnedBill.HandledTime = now;
                dbContext.Set<Entity.EMaterialReturnedBill>().Add(materialReturnedBill);

                if (maintenanceBill.ServiceItemCount == 0)
                {
                    // 没有服务项目
                    if (maintenanceBill.MaterialCount == 1)
                    {
                        maintenanceBill.MaterialStatus = Constant.MaintenanceBillStatus.MaterialStatus.Wait;
                        maintenanceBill.Status = Constant.MaintenanceBillStatus.WaitDispatching;
                    }
                    else
                    {
                        if (dbContext.Set<Entity.EMaterialRequisitionBill>().Where(p => p.MaintenanceBillId == materialReturnedBill.MaintenanceBillId
                            && p.Id != materialRequisitionBill.Id
                            && p.Status != Constant.MaterialRequisitionStatus.Returned).Select(p => p.Id).Count() > 0)
                        {
                            // 有其他的料已被领取
                            maintenanceBill.MaterialStatus = Constant.MaintenanceBillStatus.MaterialStatus.Requesting;
                            maintenanceBill.Status = Constant.MaintenanceBillStatus.Working;
                        }
                        else
                        {
                            maintenanceBill.MaterialStatus = Constant.MaintenanceBillStatus.MaterialStatus.Wait;
                            maintenanceBill.Status = Constant.MaintenanceBillStatus.WaitDispatching;
                        }
                    }
                }
                else
                {
                    // 没有服务项目
                    if (maintenanceBill.MaterialCount == 1)
                    {
                        maintenanceBill.MaterialStatus = Constant.MaintenanceBillStatus.MaterialStatus.Wait;
                        if(maintenanceBill.ServiceItemStatus == Constant.MaintenanceBillStatus.ServiceItemStatus.Wait)
                        {
                            maintenanceBill.Status = Constant.MaintenanceBillStatus.WaitDispatching;
                        }
                        else
                        {
                            maintenanceBill.Status = Constant.MaintenanceBillStatus.Working;
                        }
                    }
                    else
                    {
                        if (dbContext.Set<Entity.EMaterialRequisitionBill>().Where(p => p.MaintenanceBillId == materialReturnedBill.MaintenanceBillId
                            && p.Id != materialRequisitionBill.Id
                            && p.Status != Constant.MaterialRequisitionStatus.Returned).Select(p => p.Id).Count() > 0)
                        {
                            // 有其他的料已被领取
                            maintenanceBill.MaterialStatus = Constant.MaintenanceBillStatus.MaterialStatus.Requesting;
                            maintenanceBill.Status = Constant.MaintenanceBillStatus.Working;
                        }
                        else
                        {
                            maintenanceBill.MaterialStatus = Constant.MaintenanceBillStatus.MaterialStatus.Wait;
                            if (maintenanceBill.ServiceItemStatus == Constant.MaintenanceBillStatus.ServiceItemStatus.Wait)
                            {
                                maintenanceBill.Status = Constant.MaintenanceBillStatus.WaitDispatching;
                            }
                            else
                            {
                                maintenanceBill.Status = Constant.MaintenanceBillStatus.Working;
                            }
                        }
                    }
                }
                dbContext.Entry<Entity.EMaintenanceBill>(maintenanceBill).State = System.Data.Entity.EntityState.Modified;
                maintenanceBillMaterial.Status = Constant.MaintenanceBillMaterialStatus.Returned;
                dbContext.Entry<Entity.EMaintenanceBillMaterial>(maintenanceBillMaterial).State = System.Data.Entity.EntityState.Modified;

                #region 创建库存增加记录
                ServiceResult result = InlineCreateService.CreateStockIncreaseRecord(dbContext, now, maintenanceBillMaterial.Price, materialReturnedBill.Count,
                    WebUtility.CookieUtility.GetUserIdString(),
                    Constant.BillTypes.MaterialReturnedBill,
                    materialReturnedBill.WarehouseId,
                    materialReturnedBill.MaterialId,
                    materialReturnedBill.Id,
                    materialReturnedBill.Number);
                if (result.IsSuccess == false)
                {
                    return result;
                }
                #endregion

                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateMaterialReturnedBill error,ex:{0}", ex));
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.MaterialReturnedBill);
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        public ServiceResult CreatePackage(Entity.EPackage package, Entity.ESalesPrice[] priceArray,
            Entity.EPackageItem[] itemArray, Entity.EPackageScope[] scopeArray)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                DateTime now = DateTime.Now;
                package.Id = Guid.NewGuid();
                package.CreatedTime = now;
                package.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                package.Status = Constant.CommonStatus.Disabled;

                if (priceArray != null && priceArray.Length > 0)
                {
                    for (int index = 0; index < priceArray.Length; index++)
                    {
                        Entity.ESalesPrice item = priceArray[index];
                        item.Id = Guid.NewGuid();
                        item.TargetId = package.Id;
                        item.TargetType = Constant.SalePriceTargetTypes.Package;
                        item.CreatedTime = now;
                        item.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                        item.Status = Constant.CommonStatus.Enabled;
                        dbContext.Set<Entity.ESalesPrice>().Add(item);
                    }
                }

                decimal marketValue = 0;
                if (itemArray != null && itemArray.Length > 0)
                {
                    for (int index = 0; index < itemArray.Length; index++)
                    {
                        Entity.EPackageItem item = itemArray[index];
                        item.Id = Guid.NewGuid();
                        item.PackageId = package.Id;
                        marketValue += item.MarketPrice;
                        dbContext.Set<Entity.EPackageItem>().Add(item);
                    }
                }

                if (scopeArray != null && scopeArray.Length > 0)
                {
                    for (int index = 0; index < scopeArray.Length; index++)
                    {
                        Entity.EPackageScope scope = scopeArray[index];
                        scope.Id = Guid.NewGuid();
                        scope.PackageId = package.Id;
                        dbContext.Set<Entity.EPackageScope>().Add(scope);
                    }
                }
                else
                {
                    // 创建一个默认的适合全部的范围项
                    Entity.EPackageScope scope = new Entity.EPackageScope();
                    scope.Id = Guid.NewGuid();
                    scope.PackageId = package.Id;
                    dbContext.Set<Entity.EPackageScope>().Add(scope);
                }

                dbContext.Set<Entity.EPackage>().Add(package);
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreatePackage error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        /// <summary>
        /// 创建套餐购买单
        /// </summary>
        /// <param name="bill"></param>
        /// <returns></returns>
        public SingleResult<Entity.EPackagePurchaseBill> CreatePackagePurchaseBill(Entity.EPackagePurchaseBill bill)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                Entity.EPackage package = dbContext.Set<Entity.EPackage>().SingleOrDefault(p => p.Id == bill.PackageId);
                if (package == null)
                {
                    return new SingleResult<Entity.EPackagePurchaseBill>(1, "package not exist!");
                }

                Entity.ESalesPrice salePrice = dbContext.Set<Entity.ESalesPrice>().SingleOrDefault(p => p.TargetId == bill.PackageId && p.Channel == bill.BoughtChannel && p.Status == Constant.CommonStatus.Enabled);

                if (salePrice == null)
                {
                    return new SingleResult<Entity.EPackagePurchaseBill>(1, "price is not exist!");
                }

                DateTime now = DateTime.Now;
                bill.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.PackagePurchaseBill);
                bill.Id = Guid.NewGuid();
                bill.BoughtDate = now;
                bill.BoughtPrice = salePrice.Price;
                bill.SalesCommissionAmount = CalcUtil.CalcCommissionAmount(bill.BoughtPrice, package.SalesCommissionType, package.SalesCommission);
                bill.Status = Constant.PackagePurchaseBillStatus.Enabled;
                bill.CreatedTime = DateTime.Now;
                bill.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                dbContext.Set<Entity.EPackagePurchaseBill>().Add(bill);
                try
                {
                    dbContext.SaveChanges();
                    return new SingleResult<Entity.EPackagePurchaseBill>(bill);
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreatePackagePurchaseBill error,ex:{0}", ex));
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.PackagePurchaseBill);
                    return new SingleResult<Entity.EPackagePurchaseBill>(1, ex.Message);
                }
            }
        }

        #region settlement
        /// <summary>
        /// 创建结算单
        /// </summary>
        /// <param name="bill"></param>
        /// <param name="serviceItemArray"></param>
        /// <param name="materailArray"></param>
        /// <param name="payItemArray"></param>
        /// <param name="packageItemArray"></param>
        /// <param name="couponArray"></param>
        /// <returns></returns>
        public SingleResult<Guid> CreateSettlementBill(Entity.ESettlementBill bill, Entity.ESettlementBillServiceItem[] serviceItemArray,
            Entity.ESettlementBillMaterial[] materailArray, Entity.ESettlementBillPayItem[] payItemArray,
            Entity.ESettlementBillPackageItem[] packageItemArray, Entity.ESettlementBillCoupon[] couponArray)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                DateTime now = DateTime.Now;

                // 修改维修单的状态
                Entity.EMaintenanceBill maintenanceBill = dbContext.Set<Entity.EMaintenanceBill>().SingleOrDefault(p => p.Id
                     == bill.MaintenanceBillId);
                if (maintenanceBill == null)
                {
                    return new SingleResult<Guid>(1, "maintenance bill is not exist");
                }

                bill.Id = Guid.NewGuid();
                bill.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.SettlementBill);
                bill.CreatedTime = now;
                bill.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                bill.Status = Constant.CommonStatus.Enabled;
                decimal amount = 0;

                #region materailArray
                if (materailArray != null)
                {
                    for (int index = 0; index < materailArray.Length; index++)
                    {
                        Entity.ESettlementBillMaterial item = materailArray[index];
                        item.Id = Guid.NewGuid();
                        item.SettlementBillId = bill.Id;
                        item.Amount = item.Price * item.Count * item.Discount;
                        item.OrigAmount = item.Price * item.Count;
                        item.DisAmount = item.Price * item.Count * (1 - item.Discount);
                        amount += item.Amount;
                        dbContext.Set<Entity.ESettlementBillMaterial>().Add(item);
                    }
                }
                #endregion

                #region payItemArray
                if (payItemArray != null)
                {
                    for (int index = 0; index < payItemArray.Length; index++)
                    {
                        Entity.ESettlementBillPayItem item = payItemArray[index];
                        item.Id = Guid.NewGuid();
                        item.SettlementBillId = bill.Id;
                        if (item.Type == Constant.PayItemTypes.Discount)
                        {
                            // 优惠-金额
                            amount -= item.Amount;
                        }
                        else
                        {
                            // 付费+金额
                            amount += item.Amount;
                        }
                        dbContext.Set<Entity.ESettlementBillPayItem>().Add(item);
                    }
                }
                #endregion

                // 对应服务项的套餐列表
                List<Entity.EPackageItem> packageItemList = new List<Entity.EPackageItem>();

                decimal pkgReduceAmount = 0.0m;

                #region 减扣套餐中的代金券, 并产生套餐使用记录
                if (packageItemArray != null && packageItemArray.Length > 0)
                {
                    for (int index = 0; index < packageItemArray.Length; index++)
                    {
                        Entity.ESettlementBillPackageItem item = packageItemArray[index];
                        item.Id = Guid.NewGuid();
                        item.SettlementBillId = bill.Id;

                        Entity.EPackageInstanceItem packageInstanceItem = dbContext.Set<Entity.EPackageInstanceItem>().SingleOrDefault(p => p.Id == item.PackageInstanceItemId);
                        Entity.EPackageItem packageItem = dbContext.Set<Entity.EPackageItem>().SingleOrDefault(p => p.Id == packageInstanceItem.PackageItemId);
                        if (packageItem.Type == Constant.PackageItemTypes.Voucher)
                        {
                            // 优惠卷，直接-金额
                            amount -= packageItem.Value;
                            pkgReduceAmount += packageItem.Value;
                            // 修改剩余数量
                            packageInstanceItem.Value = 0;
                        }
                        else
                        {
                            packageItemList.Add(packageItem);
                            // 修改剩余数量
                            packageInstanceItem.Value -= item.UseCount;
                            if (packageInstanceItem.Value < 0)
                            {
                                packageInstanceItem.Value = 0;
                            }
                        }

                        dbContext.Set<Entity.ESettlementBillPackageItem>().Add(item);
                        dbContext.Entry<Entity.EPackageInstanceItem>(packageInstanceItem).State = System.Data.Entity.EntityState.Modified;

                        // 产生一条套餐使用记录
                        Entity.EPackageInstanceItemChangedRecord piiChangedRecord = new Entity.EPackageInstanceItemChangedRecord();
                        piiChangedRecord.Id = Guid.NewGuid();
                        piiChangedRecord.BillId = bill.Id;
                        piiChangedRecord.BillType = Constant.BillTypes.SettlementBill;
                        piiChangedRecord.BusinessId = bill.BusinessId;
                        piiChangedRecord.StationId = bill.StationId;
                        piiChangedRecord.PackageInstanceId = item.PackageInstanceId;
                        piiChangedRecord.PackageInstanceItemId = item.PackageInstanceItemId;
                        if (packageItem.Type == Constant.PackageItemTypes.Voucher)
                        {
                            // 代金券全部减掉
                            piiChangedRecord.Count = packageItem.Value;
                        }
                        else
                        {
                            piiChangedRecord.Count = item.UseCount;
                        }
                        piiChangedRecord.RemainingCount = packageInstanceItem.Value;
                        piiChangedRecord.Type = Constant.PackageInstanceItemChangedTypes.Decrease;
                        piiChangedRecord.CreatedTime = now;
                        piiChangedRecord.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                        dbContext.Set<Entity.EPackageInstanceItemChangedRecord>().Add(piiChangedRecord);
                    }
                }
                #endregion

                #region packageItemArray and serviceItem
                if (serviceItemArray != null)
                {
                    if (packageItemList.Count > 0)
                    {
                        #region serviceItemArray
                        for (int index = 0; index < serviceItemArray.Length;)
                        {
                            Entity.ESettlementBillServiceItem item = serviceItemArray[index];
                            item.Id = Guid.NewGuid();
                            item.SettlementBillId = bill.Id;
                            item.Amount = item.Price * item.Hour * item.Discount;
                            item.OrigAmount = item.Price * item.Hour;

                            bool redurceByPacage = false;
                            for (int piIndex = 0; piIndex < packageItemList.Count; piIndex++)
                            {
                                // 判断是否有套餐项可抵消
                                if (packageItemList[piIndex].Type == Constant.PackageItemTypes.ServiceItem)
                                {
                                    Guid tagServiceItemId = new Guid(packageItemList[piIndex].TagData);
                                    if (item.ServiceItemId == tagServiceItemId)
                                    {
                                        pkgReduceAmount += item.OrigAmount;

                                        packageItemList.RemoveAt(piIndex);
                                        item.SettlementType = Constant.SettlementTypes.ByPackage;
                                        redurceByPacage = true;
                                        break;
                                    }
                                    else
                                    {
                                        index++;
                                    }
                                }
                            }
                            if (redurceByPacage == false)
                            {
                                item.SettlementType = Constant.SettlementTypes.ByPay;
                                amount += item.Amount;
                            }
                            dbContext.Set<Entity.ESettlementBillServiceItem>().Add(item);
                        }
                        #endregion
                    }
                    else
                    {
                        #region 无套餐 计算 serviceItemArray
                        for (int index = 0; index < serviceItemArray.Length; index++)
                        {
                            Entity.ESettlementBillServiceItem item = serviceItemArray[index];
                            item.Id = Guid.NewGuid();
                            item.SettlementBillId = bill.Id;
                            item.Amount = item.Price * item.Hour * item.Discount;
                            item.OrigAmount = item.Price * item.Hour;
                            item.DisAmount = item.Price * item.Hour * (1 - item.Discount);
                            amount += item.Amount;
                            dbContext.Set<Entity.ESettlementBillServiceItem>().Add(item);
                        }
                        #endregion
                    }
                }
                #endregion

                #region couponArray
                if (couponArray != null)
                {
                    for (int index = 0; index < couponArray.Length; index++)
                    {
                        Entity.ESettlementBillCoupon coupon = couponArray[index];
                        coupon.Id = Guid.NewGuid();
                        coupon.SettlementBillId = bill.Id;
                        amount -= coupon.Amount;
                        dbContext.Set<Entity.ESettlementBillCoupon>().Add(coupon);
                    }
                }
                #endregion

                bill.Amount = amount;
                bill.PkgReduceAmount = pkgReduceAmount;
                dbContext.Set<Entity.ESettlementBill>().Add(bill);

                maintenanceBill.Status = Constant.MaintenanceBillStatus.WaitCheckOut;
                dbContext.Entry<Entity.EMaintenanceBill>(maintenanceBill).State = System.Data.Entity.EntityState.Modified;


                PrivateCreateSerivce.CreateBillHeader(dbContext, bill.Id, bill.Number, Constant.BillTypes.SettlementBill, bill.CreatedTime, bill.Creator);

                try
                {
                    dbContext.SaveChanges();
                    return new SingleResult<Guid>(bill.Id);
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateSettlementBill error,ex:{0}", ex));
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.SettlementBill);
                    return new SingleResult<Guid>(1, ex.Message);
                }
            }
        }
        #endregion

        #region recharge
        public ServiceResult CreateRechargeItem(Entity.ERechargeItem item)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                DateTime now = DateTime.Now;
                item.Id = Guid.NewGuid();
                item.CreatedTime = now;
                item.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                item.Status = Constant.CommonStatus.Enabled;

                dbContext.Set<Entity.ERechargeItem>().Add(item);
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateRechargeItem error,ex:{0}", ex));
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        public SingleResult<Guid> CreateRechargeBill(Entity.ERechargeBill bill)
        {
            if (bill.RechargeChannel != Constant.RechargeChannels.RechargeItem)
            {
                return new SingleResult<Guid>(1, "RechargeChannel not support");
            }
            if (bill.RechargeChannel == Constant.RechargeChannels.RechargeItem &&
                bill.RechargeItemId == null)
            {
                return new SingleResult<Guid>(1, "RechargeItemId is null");
            }

            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                if (bill.RechargeChannel == Constant.RechargeChannels.RechargeItem)
                {
                    Entity.ERechargeItem rechargeItem = dbContext.Set<Entity.ERechargeItem>().SingleOrDefault(p => p.Id == bill.RechargeItemId.Value);
                    if (rechargeItem == null)
                    {
                        return new SingleResult<Guid>(1, "RechargeItem not exist");
                    }

                    Entity.ESalesPrice salePrice = dbContext.Set<Entity.ESalesPrice>().SingleOrDefault(p => p.TargetId == rechargeItem.Id && p.TargetType == Constant.SalePriceTargetTypes.RechargeItem && p.Channel == bill.BoughtChannel);
                    if (salePrice == null)
                    {
                        return new SingleResult<Guid>(1, "salePrice not exist");
                    }
                    bill.Amount = rechargeItem.Price;
                    bill.BoughtPrice = salePrice.Price;
                    bill.SalesCommissionAmount = CalcUtil.CalcCommissionAmount(bill.BoughtPrice, rechargeItem.SalesCommissionType, rechargeItem.SalesCommission);
                }

                DateTime now = DateTime.Now;

                bill.Id = Guid.NewGuid();
                bill.BoughtDate = now;
                bill.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.RechargeBill);
                bill.CreatedTime = now;
                bill.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                bill.Status = Constant.CommonBillStatus.Enabled;


                dbContext.Set<Entity.ERechargeBill>().Add(bill);
                try
                {
                    dbContext.SaveChanges();
                    return new SingleResult<Guid>(bill.Id);
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateRechargeBill error,ex:{0}", ex));
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.RechargeBill);
                    return new SingleResult<Guid>(1, ex.Message);
                }
            }
        }
        #endregion

        #region capital
        public ServiceResult CreateCapticalIncreaseBill(Entity.ECapitalIncreaseBill bill, Entity.EPayRecord[] payRecordArray)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                DateTime now = DateTime.Now;
                bill.Id = Guid.NewGuid();
                bill.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.CapitalIncreaseBill);
                bill.Status = Constant.CommonStatus.Enabled;
                bill.CreatedTime = now;
                bill.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();

                if (payRecordArray != null)
                {
                    for (int index = 0; index < payRecordArray.Length; index++)
                    {
                        Entity.EPayRecord payRecord = payRecordArray[index];
                        payRecord.Id = Guid.NewGuid();
                        payRecord.SortIndex = index;
                        payRecord.BillId = bill.Id;
                        payRecord.BillType = Constant.BillTypes.CapitalIncreaseBill;
                        payRecord.CreatedTime = now;
                        payRecord.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                        
                        bill.Amount += payRecord.PayAmount;

                        dbContext.Set<Entity.EPayRecord>().Add(payRecord);
                    }
                }

                // 生成资金变更记录
                Entity.ECapitalChangedRecord capitalChangedRecord = new Entity.ECapitalChangedRecord();
                capitalChangedRecord.Id = Guid.NewGuid();
                capitalChangedRecord.BusinessId = bill.BusinessId;
                capitalChangedRecord.StationId = bill.StationId;
                capitalChangedRecord.ChangedType = bill.ChangedType;
                capitalChangedRecord.CapitalRole = bill.PayerRole;
                capitalChangedRecord.CapitalRoleType = bill.PayerRoleType;
                capitalChangedRecord.Amount = bill.Amount;
                capitalChangedRecord.BillId = bill.Id;
                capitalChangedRecord.BillNumber = bill.Number;
                capitalChangedRecord.BillType = Constant.BillTypes.CapitalIncreaseBill;
                capitalChangedRecord.CreatedTime = now;
                capitalChangedRecord.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                dbContext.Set<Entity.ECapitalChangedRecord>().Add(capitalChangedRecord);

                dbContext.Set<Entity.ECapitalIncreaseBill>().Add(bill);
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateCapticalIncreaseBill error,ex:{0}", ex));
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.CapitalIncreaseBill);
                    return new ServiceResult(1, ex.Message);
                }
            }
        }

        public ServiceResult CreateCapticalDecreaseBill(Entity.ECapitalDecreaseBill bill, Entity.EPayRecord[] payRecordArray)
        {
            using (ASMSDbContext dbContext = new ASMSDbContext())
            {
                DateTime now = DateTime.Now;
                bill.Id = Guid.NewGuid();
                bill.Number = Server.ServerData.Instance.BeginNewBillSeedString(dbContext, NumberHeader.CapitalDecreaseBill);
                bill.Status = Constant.CommonStatus.Enabled;
                bill.CreatedTime = now;
                bill.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();

                decimal amount = 0;
                if (payRecordArray != null)
                {
                    for (int index = 0; index < payRecordArray.Length; index++)
                    {
                        Entity.EPayRecord payRecord = payRecordArray[index];
                        payRecord.Id = Guid.NewGuid();
                        payRecord.SortIndex = index;
                        payRecord.BillId = bill.Id;
                        payRecord.BillType = Constant.BillTypes.CapitalDecreaseBill;
                        payRecord.CreatedTime = now;
                        payRecord.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();

                        amount += payRecord.PayAmount;

                        dbContext.Set<Entity.EPayRecord>().Add(payRecord);
                    }
                }
                bill.Amount = amount;
                dbContext.Set<Entity.ECapitalDecreaseBill>().Add(bill);

                // 生成资金变更记录
                Entity.ECapitalChangedRecord capitalChangedRecord = new Entity.ECapitalChangedRecord();
                capitalChangedRecord.Id = Guid.NewGuid();
                capitalChangedRecord.BusinessId = bill.BusinessId;
                capitalChangedRecord.StationId = bill.StationId;
                capitalChangedRecord.ChangedType = bill.ChangedType;
                capitalChangedRecord.Amount = bill.Amount;
                capitalChangedRecord.CapitalRole = bill.PayeeRole;
                capitalChangedRecord.CapitalRoleType = bill.PayeeRoleType;
                capitalChangedRecord.BillId = bill.Id;
                capitalChangedRecord.BillNumber = bill.Number;
                capitalChangedRecord.BillType = Constant.BillTypes.CapitalDecreaseBill;
                capitalChangedRecord.CreatedTime = now;
                capitalChangedRecord.Creator = Sunboxsoft.ASMS.WebUtility.CookieUtility.GetUserIdString();
                dbContext.Set<Entity.ECapitalChangedRecord>().Add(capitalChangedRecord);
                try
                {
                    dbContext.SaveChanges();
                    return new ServiceResult();
                }
                catch (Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTag, string.Format("CreateCapticalDecreaseBill error,ex:{0}", ex));
                    Server.ServerData.Instance.CancelNewBillSeed(NumberHeader.CapitalDecreaseBill);
                    return new ServiceResult(1, ex.Message);
                }
            }
        }
        #endregion

    }
}
